package com.zyf.receiver;

import com.rabbitmq.client.Channel;
import com.zyf.constant.MqConst;
import com.zyf.model.hosp.Schedule;
import com.zyf.service.RabbitService;
import com.zyf.service.ScheduleService;
import com.zyf.vo.msm.MsmVo;
import com.zyf.vo.order.OrderMqVo;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/** 医院排班 mq 监听器
 * @author zyf
 * @date 2021年05月31日 18:05
 */
@Component
public class HospitalReceiver {

    @Autowired
    private ScheduleService scheduleService;

    @Autowired
    private RabbitService rabbitService;

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = MqConst.QUEUE_ORDER, durable = "true"),
            exchange = @Exchange(value = MqConst.EXCHANGE_DIRECT_ORDER),
            key = {MqConst.ROUTING_ORDER}
    ))
    public void receiver(OrderMqVo orderMqVo, Message message, Channel channel){
        if(null !=orderMqVo.getAvailableNumber()) {
            //下单成功更新预约数
            Schedule schedule = scheduleService.getScheduleById(orderMqVo.getScheduleId());
            schedule.setReservedNumber(orderMqVo.getReservedNumber())
                    .setAvailableNumber(orderMqVo.getAvailableNumber());
            scheduleService.updateSchedule(schedule);
        }else {
            Schedule scheduleById = scheduleService.getScheduleById(orderMqVo.getScheduleId());
            int a = scheduleById.getAvailableNumber().intValue() + 1;
            scheduleById.setAvailableNumber(a);
            scheduleService.updateSchedule(scheduleById);
        }
        //发送短信
        MsmVo msmVo = orderMqVo.getMsmVo();
        if (null != msmVo){
            rabbitService.sendMessage(MqConst.EXCHANGE_DIRECT_MSM,MqConst.ROUTING_MSM_ITEM,msmVo);
        }
    }
}
